package com.agriculture.service.impl;

import com.agriculture.dto.PasswordChangeDTO;
import com.agriculture.dto.UserProfileDTO;
import com.agriculture.domain.User;
import com.agriculture.mapper.UserMapper;
import com.agriculture.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User getUserProfile(Long userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return user;
    }

    @Override
    @Transactional
    public User updateUserProfile(Long userId, UserProfileDTO profileDTO) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        user.setFullName(profileDTO.getRealName());
        user.setPhoneNumber(profileDTO.getPhone());
        user.setEmail(profileDTO.getEmail());
        user.setAddress(profileDTO.getAddress());

        userMapper.update(user);
        return user;
    }

    @Override
    @Transactional
    public void changePassword(Long userId, PasswordChangeDTO passwordDTO) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证旧密码
        if (!passwordDTO.getOldPassword().equals(user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }

        // 更新新密码
        user.setPassword(passwordDTO.getNewPassword());
        userMapper.update(user);
    }

    @Override
    public User validateUser(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            // 添加调试日志
            System.out.println("Validating user - ID: " + user.getUserId() + 
                             ", Username: " + user.getUsername());
            return user;
        }
        return null;
    }
} 